import requests
from multiprocessing import Pool, cpu_count
from time import sleep


class Login:

    def __init__(self):
        self.session = requests.session()
        self.csrf_token = None

    def req_index(self):
        url = 'https://fuwu.1688.com/sjrzdz.html?company=%E9%98%BF%E9%87%8C%E8%B4%9D%E8%B4%9D%EF%BC%88%E6%B7%B1%E' \
              '5%9C%B3%EF%BC%89%E7%BD%91%E7%BB%9C%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&name=%E6%' \
              '9D%A8%E6%99%93%E6%9F%AF&position=%E8%91%A3%E4%BA%8B%E9%95%BF&contact=13316823287&city=%E6%B7%B1%E5' \
              '%9C%B3%E5%B8%82&userIcon=https://cbu01.alicdn.com/img/ibank/2020/839/425/13464524938.jpg&userId=%E' \
              '7%94%B5%E5%95%86%E6%9C%8D%E5%8A%A1%E7%AE%A1%E5%AE%B6&pageIndex=4'

        resp = self.session.get(url)

        if resp.status_code != 200:
            raise Exception('req_index函数状态码不对')

    def get_csrf(self):
        url = "https://widget.1688.com/front/ajax/bridge.html?target=brg-0743"

        headers = {
            # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            # 'Accept-Encoding': 'gzip, deflate, br',
            # 'Host': 'widget.1688.com',
            # 'Referer': 'https://fuwu.1688.com/sjrzdz.html?company=%E9%98%BF%E9%87%8C%E8%B4%9D%E8%B4%9D%EF%BC%88%E'
            #            '6%B7%B1%E5%9C%B3%EF%BC%89%E7%BD%91%E7%BB%9C%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%'
            #            'E5%8F%B8&name=%E6%9D%A8%E6%99%93%E6%9F%AF&position=%E8%91%A3%E4%BA%8B%E9%95%BF&contact=13'
            #            '316823287&city=%E6%B7%B1%E5%9C%B3%E5%B8%82&userIcon=https://cbu01.alicdn.com/img/ibank/20'
            #            '20/839/425/13464524938.jpg&userId=%E7%94%B5%E5%95%86%E6%9C%8D%E5%8A%A1%E7%AE%A1%E5%AE%B6&'
            #            'pageIndex=4',
            # 'Upgrade-Insecure-Requests': '1',
            # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0'
        }

        resp = self.session.get(url, headers=headers)

        if resp.status_code != 200:
            raise Exception("get_csrf状态码不对")

    def get_csrf_1(self):
        """
        生成第一次csrf_token, 去请求下一个页面
        """

        url = "https://widget.1688.com/front/ajax/bridge.html?target=brg-29352"

        headers = {
            # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            # 'Accept-Encoding': 'gzip, deflate, br',
            # 'Host': 'widget.1688.com',
            # 'Referer': 'https://fuwu.1688.com/sjrzdz.html?company=%E9%98%BF%E9%87%8C%E8%B4%9D%E8%B4%9D%EF%BC%88%E'
            #            '6%B7%B1%E5%9C%B3%EF%BC%89%E7%BD%91%E7%BB%9C%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%'
            #            'E5%8F%B8&name=%E6%9D%A8%E6%99%93%E6%9F%AF&position=%E8%91%A3%E4%BA%8B%E9%95%BF&contact=13'
            #            '316823287&city=%E6%B7%B1%E5%9C%B3%E5%B8%82&userIcon=https://cbu01.alicdn.com/img/ibank/20'
            #            '20/839/425/13464524938.jpg&userId=%E7%94%B5%E5%95%86%E6%9C%8D%E5%8A%A1%E7%AE%A1%E5%AE%B6&'
            #            'pageIndex=4',
            # 'Upgrade-Insecure-Requests': '1',
            # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0'
        }

        resp = self.session.get(url, headers=headers)

        if resp.status_code != 200:
            raise Exception("get_csrf_1状态码不对")

        self.csrf_token = resp.headers['Set-Cookie'].split("; ")[0].split("=")[1]

    def get_csrf_2(self):
        """
        接上一次的csrf_token调一次接口
        """

        url = "https://widget.1688.com/front/ajax/getJsonComponent.json?namespace=QueryTpActivityGoodEmpLike" \
              "&widgetId=QueryTpActivityGoodEmpLike&methodName=execute&params=%7B%22bizType%22%3A%22tp_activ" \
              "ity_partner_01%22%2C%22pageSize%22%3A100%2C%22pageNo%22%3A2%7D&bizType=tp_activity_partner_01&" \
              "pageSize=100&pageNo=2&__mbox_csrf_token={}".format(self.csrf_token)

        headers = {
            # 'Accept': 'application/json, text/javascript, */*; q=0.01',
            # 'Accept-Encoding':'gzip, deflate, br',
            # 'Connection':'keep-alive',
            # 'Host': 'widget.1688.com',
            'Referer': 'https://widget.1688.com/front/ajax/bridge.html?target=brg-29352',
            # 'TE':'Trailers',
            # "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
            # 'X-Requested-With': 'XMLHttpRequest'
        }

        resp = self.session.get(url, headers=headers)

        if resp.status_code != 200:
            raise Exception("get_csrf_2: 验证第一步状态码失败")

    def get_csrf_3(self):
        """
        再次刷新csrf_token, 用来请求投票接口
        """

        url = "https://widget.1688.com/front/ajax/bridge.html?target=brg-42883"

        headers = {
            # 'Accept': 'application/json, text/javascript, */*; q=0.01',
            # 'Accept-Encoding':'gzip, deflate, br',
            # 'Connection':'keep-alive',
            # 'Host': 'widget.1688.com',
            'Referer': 'https://widget.1688.com/front/ajax/bridge.html?target=brg-29352',
            # 'TE':'Trailers',
            # "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
            # 'X-Requested-With': 'XMLHttpRequest'
        }

        resp = self.session.get(url, headers=headers)

        if resp.status_code != 200:
            raise Exception("get_csrf_2: 验证第一步状态码失败")

        self.csrf_token = resp.headers['Set-Cookie'].split("; ")[0].split("=")[1]

    def get_ticket(self):

        url = "https://widget.1688.com/front/ajax/getJsonComponent.json?namespace=TpAddLike&widgetId=TpAddLike&me" \
              "thodName=execute&params=%7B%22bizType%22%3A%22tp_activity_partner_01%22%2C%22formId%22%3A%222911" \
              "55%22%7D&bizType=tp_activity_partner_01&formId=291155&__mbox_csrf_token={}".format(self.csrf_token)

        headers = {
            'Referer': 'https://widget.1688.com/front/ajax/bridge.html?target=brg-42883'
        }

        resp = self.session.get(url, headers=headers)


def func(num):
    count = 0

    while 1:
        try:
            spider = Login()
            spider.req_index()
            spider.get_csrf()
            spider.get_csrf_1()  # 开始获取token
            spider.get_csrf_2()
            spider.get_csrf_3()
            spider.get_ticket()
            print(f"进程{num}已经刷了{count}次")
            count += 1
        except Exception as e:
            print(e)
            sleep(5)


if __name__ == '__main__':
    cpu_num = cpu_count()
    # cpu_num = 10
    print(f"获得CPU数量: {cpu_num}")

    # p = Pool(cpu_num)
    # for i in range(cpu_num):
    #     p.apply_async(func, args=(i,))

    # p.close()
    # p.join()
    # 
    p = Pool(20)
    for i in range(20):
        p.apply_async(func, args=(i,))

    p.close()
    p.join()
    # func(1)